<template>
  <div class="admin-announcements-container">
    <div class="page-header">
      <div class="header-title">
        <span class="header-desc">管理系统公告和通知</span>
      </div>
      <el-button type="primary" icon="el-icon-plus" @click="drawer = true">添加公告</el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-input
        placeholder="搜索公告标题"
        v-model="searchKeyword"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @keyup.enter.native="handleSearch"
      ></el-input>
      <el-select v-model="statusFilter" placeholder="状态筛选" clearable class="filter-select">
        <el-option label="全部状态" value=""></el-option>
        <el-option label="草稿" value="draft"></el-option>
        <el-option label="已发布" value="published"></el-option>
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="date-range"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
      <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
      <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
    </div>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <div class="table-operations" v-if="multipleSelection.length > 0">
        <span class="selected-count">已选择 {{ multipleSelection.length }} 项</span>
        <el-button size="small" type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
        <el-button size="small" type="success" icon="el-icon-check" @click="handleBatchPublish">批量发布</el-button>
      </div>

      <el-table 
        :data="filteredAnnounList" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="announcementId" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'published' ? 'success' : 'info'">
              {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="content" label="内容" min-width="250" show-overflow-tooltip></el-table-column>
        <el-table-column prop="targetAudience" label="目标受众" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="有效期" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.validFrom && scope.row.validUntil">
              <div>{{ formatDate(scope.row.validFrom) }}</div>
              <div class="date-separator">至</div>
              <div>{{ formatDate(scope.row.validUntil) }}</div>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="170">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              icon="el-icon-edit" 
              @click="handleEdit(scope.row)"
              circle
            ></el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'published' ? 'warning' : 'success'" 
              :icon="scope.row.status === 'published' ? 'el-icon-close' : 'el-icon-check'" 
              @click="toggleStatus(scope.row)"
              circle
            ></el-button>
            <el-button 
              size="mini" 
              type="danger" 
              icon="el-icon-delete" 
              @click="confirmDelete(scope.row)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredAnnounList.length">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑公告抽屉 -->
    <el-drawer 
      :title="isEdit ? '编辑公告' : '添加公告'" 
      :visible.sync="drawer" 
      direction="rtl" 
      size="50%" 
      :before-close="handleDrawerClose"
      custom-class="announcement-drawer"
    >
      <div class="drawer-content">
        <div class="drawer-header">
          <h3>{{ isEdit ? '编辑公告信息' : '创建新公告' }}</h3>
        </div>

        <el-form 
          :model="announcementForm" 
          label-width="120px" 
          ref="announcementForm" 
          :rules="rules"
          class="announcement-form"
        >
        <el-form-item label="标题" prop="title">
            <el-input v-model="announcementForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
          
        <el-form-item label="内容" prop="content">
            <el-input 
              type="textarea" 
              v-model="announcementForm.content" 
              placeholder="请输入公告内容"
              :rows="6"
            ></el-input>
        </el-form-item>
          
        <el-form-item label="关联用户ID" prop="userId">
            <el-input-number 
              v-model="announcementForm.userId" 
              :min="1"
              placeholder="请输入关联用户ID"
              style="width: 100%"
            ></el-input-number>
        </el-form-item>
          
        <el-form-item label="状态" prop="status">
            <el-select v-model="announcementForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="草稿" value="draft"></el-option>
            <el-option label="发布" value="published"></el-option>
          </el-select>
        </el-form-item>
          
        <el-form-item label="目标受众" prop="targetAudience">
            <el-input 
              v-model="announcementForm.targetAudience" 
              placeholder="请输入目标受众，如：全体用户、VIP用户等"
            ></el-input>
        </el-form-item>
          
          <el-form-item label="有效期" required>
            <el-col :span="11">
              <el-form-item prop="validFrom">
          <el-date-picker
            v-model="announcementForm.validFrom"
            type="datetime"
                  placeholder="开始时间"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
        </el-form-item>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">至</el-col>
            <el-col :span="11">
              <el-form-item prop="validUntil">
          <el-date-picker
            v-model="announcementForm.validUntil"
            type="datetime"
                  placeholder="结束时间"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
        </el-form-item>
          
          <el-form-item class="form-buttons">
            <el-button type="primary" @click="submitForm('announcementForm')" :loading="submitLoading">{{ isEdit ? '保存' : '提交' }}</el-button>
          <el-button @click="resetForm('announcementForm')">重置</el-button>
            <el-button @click="drawer = false">取消</el-button>
        </el-form-item>
      </el-form>
      </div>
            </el-drawer>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除"{{ currentRow ? currentRow.title : '' }}"吗？此操作不可逆。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">确定</el-button>
      </span>
    </el-dialog>

    <!-- 批量操作确认对话框 -->
    <el-dialog
      :title="batchActionTitle"
      :visible.sync="batchDialogVisible"
      width="30%">
      <span>{{ batchActionMessage }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchAction">确定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            drawer: false,
      isEdit: false,
      loading: false,
      submitLoading: false,
      deleteDialogVisible: false,
      batchDialogVisible: false,
      currentRow: null,
      batchActionType: '',
      batchActionTitle: '',
      batchActionMessage: '',
      searchKeyword: '',
      statusFilter: '',
      dateRange: [],
      currentPage: 1,
      pageSize: 10,
      multipleSelection: [],
      announcementForm: {
        title: '',
        content: '',
        userId: 1,
        status: 'draft',
        targetAudience: '',
        validFrom: '',
        validUntil: ''
      },
            rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请输入关联用户ID', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择公告状态', trigger: 'change' }
        ],
        validFrom: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        validUntil: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
            },
            announList: []
        };
    },
  computed: {
    filteredAnnounList() {
      let result = [...this.announList];
      
      // 关键字搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(item => 
          (item.title && item.title.toLowerCase().includes(keyword)) || 
          (item.content && item.content.toLowerCase().includes(keyword))
        );
      }
      
      // 状态筛选
      if (this.statusFilter) {
        result = result.filter(item => item.status === this.statusFilter);
      }
      
      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]).getTime();
        const endDate = new Date(this.dateRange[1]).getTime();
        
        result = result.filter(item => {
          const createdAt = new Date(item.createdAt).getTime();
          return createdAt >= startDate && createdAt <= endDate;
        });
      }
      
      return result;
    }
  },
    methods: {
    // 提交表单
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
          this.submitLoading = true;
                    this.request.post('/announcements', this.announcementForm)
                        .then(response => {
                            console.log('announcements added:', response.data);
              this.$message.success(this.isEdit ? '公告更新成功' : '公告创建成功');
              this.drawer = false;
                            this.getCouponsList();
                            this.resetForm(formName);
                        })
                        .catch(error => {
                            console.error('Failed to add coupon:', error);
              this.$message.error('操作失败，请重试');
            })
            .finally(() => {
              this.submitLoading = false;
                        });
                } else {
                    console.log('Error submitting form');
                    return false;
                }
            });
        },
    
    // 重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    
    // 获取公告列表
        getCouponsList() {
      this.loading = true;
            this.request.get('/announcements')
                .then(response => {
                    this.announList = response.data;
                })
                .catch(error => {
                    console.error('Failed to fetch coupons list:', error);
          this.$message.error('获取公告列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 编辑公告
    handleEdit(row) {
      this.isEdit = true;
      this.announcementForm = { ...row };
      this.drawer = true;
    },
    
    // 删除确认对话框
    confirmDelete(row) {
      this.currentRow = row;
      this.deleteDialogVisible = true;
    },
    
    // 处理删除
    handleDelete() {
      // 此处应该调用删除API
      console.log('删除公告:', this.currentRow);
      this.$message.success('删除成功');
      this.deleteDialogVisible = false;
      this.currentRow = null;
      // 重新加载数据
      this.getCouponsList();
    },
    
    // 切换状态
    toggleStatus(row) {
      const newStatus = row.status === 'published' ? 'draft' : 'published';
      const statusText = newStatus === 'published' ? '发布' : '下架';
      
      // 这里应该是状态更新API调用
      console.log(`${statusText}公告:`, row);
      this.$message.success(`${statusText}成功`);
      
      // 重新加载数据
      this.getCouponsList();
    },
    
    // 多选变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    // 批量删除
    handleBatchDelete() {
      this.batchActionType = 'delete';
      this.batchActionTitle = '批量删除';
      this.batchActionMessage = `确定要删除选中的 ${this.multipleSelection.length} 条公告吗？此操作不可逆。`;
      this.batchDialogVisible = true;
    },
    
    // 批量发布
    handleBatchPublish() {
      this.batchActionType = 'publish';
      this.batchActionTitle = '批量发布';
      this.batchActionMessage = `确定要发布选中的 ${this.multipleSelection.length} 条公告吗？`;
      this.batchDialogVisible = true;
    },
    
    // 确认批量操作
    confirmBatchAction() {
      if (this.batchActionType === 'delete') {
        // 这里应该是批量删除API调用
        console.log('批量删除:', this.multipleSelection);
        this.$message.success('批量删除成功');
      } else if (this.batchActionType === 'publish') {
        // 这里应该是批量发布API调用
        console.log('批量发布:', this.multipleSelection);
        this.$message.success('批量发布成功');
      }
      
      this.batchDialogVisible = false;
      // 重新加载数据
      this.getCouponsList();
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.statusFilter = '';
      this.dateRange = [];
      this.currentPage = 1;
    },
    
    // 改变每页显示数量
    handleSizeChange(val) {
      this.pageSize = val;
    },
    
    // 改变页码
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '--';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '--';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 抽屉关闭前处理
    handleDrawerClose(done) {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isEdit = false;
        done();
      }).catch(() => {});
        }
    },
    created() {
        this.getCouponsList();
    }
};
</script>

<style scoped>
.admin-announcements-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.header-desc {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 250px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.filter-select {
  width: 150px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.date-range {
  width: 350px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.selected-count {
  margin-right: 15px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drawer-content {
  padding: 20px;
}

.drawer-header {
  margin-bottom: 20px;
}

.drawer-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.announcement-form {
  padding: 0 10px;
}

.form-buttons {
  margin-top: 30px;
  text-align: right;
}

.date-separator {
  text-align: center;
  color: #909399;
  margin: 2px 0;
}

::v-deep .announcement-drawer .el-drawer__header {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  font-size: 18px;
  font-weight: bold;
}
</style>